/**
 * 分数管理器
 * 负责分数计算、等级管理和成就系统
 */
export default class ScoreManager {
    constructor(gameManager) {
        this.gameManager = gameManager;
        this.currentScore = 0;
        this.bestScore = 0;
        this.combo = 0;
        this.maxCombo = 0;
        this.totalCalculations = 0;
        this.achievements = [];
        
        // 从本地存储加载最佳分数
        this.loadBestScore();
    }

    /**
     * 重置分数
     */
    reset() {
        this.currentScore = 0;
        this.combo = 0;
        this.totalCalculations = 0;
        console.log('分数已重置');
    }

    /**
     * 添加分数
     */
    addScore(points) {
        if (points <= 0) return;
        
        // 基础分数
        let scoreToAdd = points;
        
        // 连击加成
        this.combo++;
        if (this.combo > 1) {
            const comboBonus = Math.floor(points * (this.combo * 0.1));
            scoreToAdd += comboBonus;
            console.log(`连击 x${this.combo}! 获得额外 ${comboBonus} 分`);
        }
        
        this.currentScore += scoreToAdd;
        this.totalCalculations++;
        
        // 更新最大连击
        if (this.combo > this.maxCombo) {
            this.maxCombo = this.combo;
        }
        
        // 检查是否创造新纪录
        if (this.currentScore > this.bestScore) {
            this.bestScore = this.currentScore;
            this.saveBestScore();
            console.log('新纪录！', this.bestScore);
        }
        
        // 检查成就
        this.checkAchievements();
        
        console.log(`获得 ${scoreToAdd} 分，当前总分: ${this.currentScore}`);
    }

    /**
     * 重置连击
     */
    resetCombo() {
        if (this.combo > 0) {
            console.log(`连击结束，最高连击: ${this.combo}`);
            this.combo = 0;
        }
    }

    /**
     * 检查成就
     */
    checkAchievements() {
        const achievements = [
            {
                id: 'first_calculation',
                name: '初次尝试',
                description: '完成第一次计算',
                condition: () => this.totalCalculations >= 1
            },
            {
                id: 'combo_master',
                name: '连击大师',
                description: '达成10连击',
                condition: () => this.combo >= 10
            },
            {
                id: 'score_100',
                name: '百分达人',
                description: '单局得分达到100分',
                condition: () => this.currentScore >= 100
            },
            {
                id: 'score_500',
                name: '五百强者',
                description: '单局得分达到500分',
                condition: () => this.currentScore >= 500
            },
            {
                id: 'calculation_50',
                name: '计算专家',
                description: '完成50次计算',
                condition: () => this.totalCalculations >= 50
            }
        ];

        achievements.forEach(achievement => {
            if (!this.hasAchievement(achievement.id) && achievement.condition()) {
                this.unlockAchievement(achievement);
            }
        });
    }

    /**
     * 解锁成就
     */
    unlockAchievement(achievement) {
        this.achievements.push(achievement.id);
        console.log(`🏆 成就解锁: ${achievement.name} - ${achievement.description}`);
        
        // 这里可以触发成就解锁的UI效果
        // this.gameManager.uiManager.showAchievement(achievement);
    }

    /**
     * 检查是否拥有成就
     */
    hasAchievement(achievementId) {
        return this.achievements.includes(achievementId);
    }

    /**
     * 保存最佳分数到本地存储
     */
    saveBestScore() {
        try {
            wx.setStorageSync('bestScore', this.bestScore);
        } catch (e) {
            console.log('保存最佳分数失败:', e);
        }
    }

    /**
     * 从本地存储加载最佳分数
     */
    loadBestScore() {
        try {
            const savedScore = wx.getStorageSync('bestScore');
            if (savedScore) {
                this.bestScore = savedScore;
                console.log('加载最佳分数:', this.bestScore);
            }
        } catch (e) {
            console.log('加载最佳分数失败:', e);
        }
    }

    /**
     * 计算等级
     */
    calculateLevel() {
        // 每100分升一级
        return Math.floor(this.currentScore / 100) + 1;
    }

    /**
     * 计算当前等级的进度
     */
    getLevelProgress() {
        const currentLevel = this.calculateLevel();
        const pointsForCurrentLevel = (currentLevel - 1) * 100;
        const pointsInCurrentLevel = this.currentScore - pointsForCurrentLevel;
        return {
            level: currentLevel,
            progress: pointsInCurrentLevel,
            maxProgress: 100
        };
    }

    /**
     * 获取统计信息
     */
    getStats() {
        return {
            currentScore: this.currentScore,
            bestScore: this.bestScore,
            combo: this.combo,
            maxCombo: this.maxCombo,
            totalCalculations: this.totalCalculations,
            level: this.calculateLevel(),
            achievements: this.achievements.length
        };
    }

    /**
     * 获取当前分数
     */
    getCurrentScore() {
        return this.currentScore;
    }

    /**
     * 获取最佳分数
     */
    getBestScore() {
        return this.bestScore;
    }

    /**
     * 获取当前连击数
     */
    getCurrentCombo() {
        return this.combo;
    }
}
